<template>
    <div class="group-container">
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>发起群聊</template>
            <template #right><i class="iconfont icon-home" @click="$router.push('/')"></i></template>
        </TridentNavBar>

        <div class="content-wrap">
            <!-- 搜索区域开始 -->
            <van-search
                v-model="params.username"
                show-action
                shape="round"
                background="#27BA9B"
                placeholder="请输入搜索关键词"
            >
                <template #action>
                    <div @click="handleSearch" style="color: #FFF;">搜索</div>
                </template>
            </van-search>
            <!-- 搜索区域结束 -->

            <div class="cell-item" @click="$router.push('/selectGroupChat')">
                <div>选择一个群</div>
                <i class="iconfont icon-youjiantou"></i>
            </div>
            <div class="cell-item">
                <div>面对面建群</div>
                <i class="iconfont icon-youjiantou"></i>
            </div>
            
            <!-- 好友区域开始 -->
            <div class="friend-box">
                <!-- 星标好友区域开始 -->
                <div class="star-friend">
                    <div class="title-panel">星标好友</div>
                     <!-- 骨架屏区域 -->
                     <TridentCellSkeleton
                        v-if="isSkeleton"
                        v-for="(index) in 7" :key="index"
                        :isLeftSecondRow="false"
                        :isRight="false"
                        :isChecked="true"
                        width="50px"
                        height="50px"
                    />

                    <div class="item-panel" v-for="(item, index) in starFriendList" :key="index">
                        <van-checkbox v-model="item.is_check" checked-color="#27BA9B" @change="handleChange($event, item)"/>
                        <div class="image">
                            <van-image
                                width="45"
                                height="45"
                                :src="item.info.avatar_url ? global.MINIO_FILE_DOMAIN + item.info.avatar_url : 'src/assets/images/default_avatar.png'"
                                fit="contain"
                            />
                        </div>
                        <div class="name">{{item.info.username}}</div>
                    </div>
                </div>
                <!-- 星标好友区域结束 -->


                <!-- 普通好友区域开始 -->
                <div class="title">普通好友</div>
                <van-index-bar
                    :sticky-offset-top="45"
                    highlight-color="#27BA9B"
                    :sticky="true"
                    :index-list="Object.keys(generalFriendList)"
                >
                    <div class="friend" v-for="(key, index) in Object.keys(generalFriendList)" :key="index">
                        <van-index-anchor :index="key"/>
                        <div class="friend-item" v-for="(value, index) in generalFriendList[key]" :key="index">
                            <van-checkbox v-model="value.is_check" checked-color="#27BA9B" @change="handleChange($event, value)"/>
                            <div class="image-panel">
                                <van-image
                                    width="50"
                                    height="50"
                                    :src="value.info.avatar_url ? global.MINIO_FILE_DOMAIN + value.info.avatar_url : 'src/assets/images/default_avatar.png'"
                                    fit="contain"
                                />
                            </div>
                            <div class="name-panel">{{value.info.username}}</div>
                        </div>
                    </div>
                </van-index-bar>
                <!-- 普通好友区域结束 -->

            </div>
            <!-- 好友区域结束 -->

            <!-- 返回顶部区域开始 -->
            <van-back-top bottom="100" right="10"><i class="iconfont icon-top" style="font-size: 30px;"></i></van-back-top>
        </div>

        <!-- 底部操作区域开始 -->
        <div class="footer-wrap">
            <div class="btn-box" :class="{actived: createGroupChatParams.member.length > 0}" @click="handleShowCreateGroupChat">完成</div>
        </div>

        <!-- 创建群聊名称弹层开始 -->
        <van-popup
            v-model:show="createGroupChatPopup"
            position="bottom"
            closeable
            round
            :style="{ height: '28%' }"
        >
            <div class="popup-wrap">
                <div class="title-box">群聊名称</div>
                <van-form @submit="handleCreateGroupChat">
                    <van-field
                        v-model="createGroupChatParams.name"
                        label="群聊名称"
                        placeholder="请输入群聊名称"
                        :rules="[{ required: true, message: '请输入群聊名称' }]"
                    />

                    <van-field
                        v-model="createGroupChatParams.note"
                        label="备注"
                        placeholder="请输入备注"
                    />
                    <div class="btn-box">
                        <van-button
                            type="primary"
                            native-type="submit"
                            round
                            block
                            color="#27BA9B"
                        >
                            保 存
                        </van-button>
                    </div>
                </van-form>
            </div>
        </van-popup>
        <!-- 创建群聊名称弹层结束 -->
    </div>
</template>

<script lang="ts" setup>
import { reqFriendListAPI } from '@/apis/friend'
import { reqCreateGroupChatAPI } from '@/apis/groupChat'
import { useUserStore } from '@/store/modules/user'
import type { Friend, FriendListParams } from '@/types/friend'
import { CreateGroupChatParams } from '@/types/groupChat'
import { pinyin } from 'pinyin-pro'
import { showSuccessToast, showToast } from 'vant'
import { inject, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

// --------------- 定义全局变量开始 ---------------
// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()

// 路由器
const router = useRouter()

// 骨架屏
const isSkeleton = ref<boolean>(false)
// --------------- 定义全局变量结束 ---------------


onMounted(async() => {
    await getFriendList()
})

// -------------- 处理复选框变化开始 --------------
const handleChange = (e: any, friend: Friend) => {
    if (e) {
        createGroupChatParams.value.member.push({
            uid: friend.info.uid,
            username: friend.info.username,
            avatar_url: friend.info.avatar_url,
            mobile: friend.info.mobile,
            is_disturb: 0,
            is_top: 0
        })
    } else {
        const index = createGroupChatParams.value.member.findIndex(item => item.uid == friend.info.uid)
        createGroupChatParams.value.member.splice(index, 1)
    }
}
// -------------- 处理复选框变化结束 --------------



// --------------- 处理创建群聊开始 ---------------
const createGroupChatParams = ref<CreateGroupChatParams>({
    name: '',
    member: [],
    note: ''
})

const createGroupChatPopup = ref<boolean>(false)

// 显示群聊弹层
const handleShowCreateGroupChat = () => {
    if (createGroupChatParams.value.member.length < 2) {
        showToast('群聊至少需要2个好友')
        return false
    }
        
    createGroupChatPopup.value = true
}

// 创建群聊
const handleCreateGroupChat = async () => {
    const result = await reqCreateGroupChatAPI(createGroupChatParams.value)
    showSuccessToast('创建群聊成功')
    setTimeout(() => {
        router.push('/chat?mode=2&gid=' + result.data.id)
    }, 1000)
}
// --------------- 处理创建群聊结束 ---------------



// --------------- 处理好友列表开始 ---------------
const params = ref<FriendListParams>({
    username: '',
    is_my_friend: 1,
    is_friend_info: 1,
    status: '1',
    page: 1,
    page_size: -1
})

// 全部好友列表
const allFriendList = ref<Friend[]>([])

// 星标好友列表
const starFriendList = ref<Friend[]>([])

// 普通好友列表
const generalFriendList: any = ref({})

// 获取好友列表
const getFriendList = async () => {
    isSkeleton.value = true
    const result = await reqFriendListAPI(params.value)
    starFriendList.value = []
    allFriendList.value = result.data.friends
    let tempFriendList: any = {}
    result.data.friends.forEach(item => {
        let is_asterisk = ''
        item.information.forEach(value => {
            if (value.uid != userStore.profile.user.uid) {
                is_asterisk = value.is_asterisk
            }
        })

        if (is_asterisk == '1') {
            starFriendList.value.push(item)
        } else  {
            let initial = pinyin(item.info.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
            
            if (!tempFriendList[initial]) {
                tempFriendList[initial] = []
            }

            tempFriendList[initial].push(item)
        }
    })

    generalFriendList.value = Object.keys(tempFriendList).sort().reduce((acc: any, key) => {
        acc[key] = tempFriendList[key];
        return acc;
    }, {});

    isSkeleton.value = false
}
// --------------- 处理好友列表结束 ---------------



// --------------- 搜索好友功能开始 ---------------
// 处理搜索
const handleSearch = () => {
    getFriendList()
}
// --------------- 搜索好友功能结束 ---------------
</script>

<style scoped lang="scss">
page,
.group-container {
    height: 100vh;
    // 内容区域开始
    .content-wrap {
        padding: 45px 0;
        .cell-item {
            height: 44px;
            line-height: 44px;
            border-bottom: 1px solid #edecec;
            padding: 0 15px;
            color:  #000;
            display: flex;
            justify-content: space-between;
            .iconfont {
                color: #edecec;
            }
        }
        
        // 好友区域开始
        .friend-box {
            padding-left: 15px;
            margin-top: 15px;
            // 星标好友区域开始
            .star-friend {
                .title-panel {
                    color: #000;
                }
                .item-panel {
                    display: flex;
                    align-items: center;
                    padding-left: 4px;
                    background-color: #fff;
                    .image {
                        width: 45px;
                        height: 45px;
                        line-height: 45px;
                        border-radius: 5px;
                        text-align: center;
                        overflow: hidden;
                        margin-left: 15px;
                        border: 1px solid #edecec;
                    }
                    .name {
                        flex: 1;
                        margin-left: 15px;
                        color: #000;
                        font-size: 14px;
                        border-bottom: 1px solid #EDEDED;
                        padding: 25px 0;
                    }
                }
            }

            .title {
                padding: 10px 0;
                color: #000;
            }

            // 普通好友区域开始
            .friend {
                padding-right: 20px;
                margin-top: 6px;
                margin-bottom: 6px;
                .friend-item {
                    background-color: #fff;
                    display: flex;
                    align-items: center;
                    padding-left: 4px;
                    border-radius: 6px;
                    padding-left: 10px;
                    .image-panel {
                        width: 45px;
                        height: 45px;
                        line-height: 45px;
                        border-radius: 5px;
                        text-align: center;
                        overflow: hidden;
                        margin-left: 15px;
                        border: 1px solid #edecec;
                        img {
                            width: 80px;
                            height: 80px;
                        }
                    }

                    &:last-child .name-panel {
                        border-bottom: none;
                    }
                    .name-panel {
                        flex: 1;
                        margin-left: 15px;
                        color: #000;
                        font-size:14px;
                        border-bottom: 1px solid #EDEDED;
                        padding: 25px 0;
                    }
                }
            }
        }
    }

    // 底部操作区域开始
    .footer-wrap {
        display: flex;
        position: fixed;
        bottom: 0;
        left: 0;
        height: 45px;
        background-color: #F7F7F7;
        width: 100%;
        justify-content: flex-end;
        align-items: center;
        border-top: 1px solid #bcbaba;
        .btn-box {
            height: 30px;
            line-height: 30px;
            border: 1px solid #c6c5c5;
            margin-right: 40px;
            width: 60px;
            text-align: center;
            border-radius: 4px;
            color: #bcbaba;
            &.actived {
                color: #27BA9B;
                border: 1px solid #27BA9B;
            }
        }
    }

    // 弹层区域开始
    .popup-wrap {
        .title-box {
            margin-top: 20px;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px
        }

        .btn-box {
            display: flex;
            justify-content: center;
            margin-top: 5px;
            padding: 0 10px;
        }
    }
}
</style>